$(document).ready(function () {
	reloadUser();
	$('#filter').keyup(function () {

		var filter = $('#filter').val().toLowerCase();
		console.log(filter);

		$('tr').show();
		if (filter.length == 0) return;

		$('tr:not(:first)').each(function () {
			console.log($(this).find(".name").text());
			if ($(this).find(".name").text().toLowerCase().indexOf(filter) == -1
			 && $(this).find(".lastname").text().toLowerCase().indexOf(filter) == -1
			 && $(this).find(".username").text().toLowerCase().indexOf(filter) == -1) {
			
				$(this).hide();
			}
		});

	});
});


function showEditModal() {
	resetForm();

	if (typeof getSelectedId() === 'undefined') {
		alert("You must select row.");
		return;
	}
	$('#submit_add').click(setUser);
	$.ajax({
		url: "/api/users/get/by/id",
		type: 'POST',
		data: {
			csrfmiddlewaretoken: $.cookie('csrftoken'), // just the token value
			id: getSelectedId()
		},
		success: function (response) {
			var users = eval(response);
			for (i = 0; i < users.length; i++) {
				$('#user_modal_title').html('Edit user: ' + users[i].id + ' <button class="btn btn btn-warning" onclick="resetForm();">Reset</button>');
				$('#id_name').val(users[i].name);
				$('#id_lastname').val(users[i].lastname);
				$('#id_username').val(users[i].username);
				$('#id_address').val(users[i].address);
				$('#id_cardNumber').val(users[i].cardNumber);
				$('#id_phoneNumber').val(users[i].phoneNumber);
				$('#id_privilage').val(users[i].privilage);
			}
		}
	});

	$('#add_user_modal').modal('show');
}

function getSelectedId() {
	return $('input[name=tab1]:checked').val()
}

function showAddModal() {
	resetForm();
	$('#submit_add').click(addUser);
	$('#user_modal_title').html('Add user <button class="btn btn btn-warning" onclick="resetForm();">Reset</button>');
	$('#add_user_modal').modal('show');
}

function reloadUser() {
	$.ajax({
		url: "/api/users/get/all/",
		type: 'POST',
		data: {
			csrfmiddlewaretoken: $.cookie('csrftoken') // just the token value
		},
		success: function (response) {
			$('#users_table_body').html('');
			var users = eval(response);
			for (i = 0; i < users.length; i++) {
				$('#users_table_body').append('<tr>' + '<td><input class="tabradio" type="radio" name="tab1" value="' + users[i].id + '" /></td><td>' + users[i].id + '</td>' + '<td class="name">' + users[i].name + '</td>' + '<td class="lastname">' + users[i].lastname + '</td>' + '<td class="username">' + users[i].username + '</td>' + '<td>' + users[i].address + '</td>' + '<td>' + users[i].cardNumber + '</td>' + '<td>' + users[i].phoneNumber + '</td>' + '<td>' + users[i].privilage + '</td>' + '</tr>');
			}
		}
	});
}

function resetForm() {
	$(":input").not(":button, :submit, :reset, :hidden,.tabradio").each(function () {
		this.value = '';
	});
}

function addUser() {

	if ($('#id_password').val() != $('#id_rePassword').val()) {
		showAlert('error', '<strong>Error! </strong>Passwords are not identical.');
		return;
	}

	$.ajax({
		url: "/api/users/add/",
		type: 'POST',
		data: {
			name: $('#id_name').val(),
			lastname: $('#id_lastname').val(),
			username: $('#id_username').val(),
			password: $('#id_password').val(),
			rePassword: $('#id_rePassword').val(),
			address: $('#id_address').val(),
			cardNumber: $('#id_cardNumber').val(),
			phoneNumber: $('#id_phoneNumber').val(),
			privilage: $('#id_privilage').val(),
			csrfmiddlewaretoken: $.cookie('csrftoken')
		},
		success: function (response) {
			var val = eval(response)[0].Error;
			if (val == 0) {
				showAlert('success', 'User added!');
				reloadUser();
				$('#add_user_modal').modal('hide');
			} else if (val == -4) showAlert('error', 'Form is not valid!');
			else if (val == -3) showAlert('error', 'Form is not valid! Some fields is not uniqe.');
		}
	})

}

function setUser() {

	if ($('#id_password').val() != $('#id_rePassword').val()) {
		showAlert('error', '<strong>Error! </strong>Passwords are not identical.');
		return;
	}

	$.ajax({
		url: "/api/users/set/",
		type: 'POST',
		data: {
			id: getSelectedId(),
			name: $('#id_name').val(),
			lastname: $('#id_lastname').val(),
			username: $('#id_username').val(),
			password: $('#id_password').val(),
			rePassword: $('#id_rePassword').val(),
			address: $('#id_address').val(),
			cardNumber: $('#id_cardNumber').val(),
			phoneNumber: $('#id_phoneNumber').val(),
			privilage: $('#id_privilage').val(),
			csrfmiddlewaretoken: $.cookie('csrftoken')
		},
		success: function (response) {
			var val = eval(response)[0].Error;
			if (val == 0) {
				showAlert('success', 'User Edited!');
				reloadUser();
			} else if (val == -4) showAlert('error', 'Form is not valid!');
			else if (val == -3) showAlert('error', 'Form is not valid! Some fields is not uniqe.');
		}
	})

}

function delUser() {

	$.ajax({
		url: "/api/users/del/",
		type: 'POST',
		data: {
			id: getSelectedId(),
			csrfmiddlewaretoken: $.cookie('csrftoken')
		},
		success: function (response) {
			var val = eval(response)[0].Error;
			if (val == 0) {
				reloadUser();
			}
		}
	});

}

function showAlert(type, message) {
	$('#alert_area').html('');
	$('#alert_area').append('<div class="alert alert-' + type + '">' + message + ' </div>');
}

function deleteUser() {
	if (typeof getSelectedId() === 'undefined') {
		alert("You must select row.");
		return;
	}
	$('#delete_modal').modal('show');
}